import requests
import json


def get_api_token_auth(username='admin', password='admin'):
    url = "http://127.0.0.1:8000/api/api-token-auth/"
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    payload = {
        "username": username,
        "password": password
    }

    ret = requests.post(url, data=json.dumps(payload), headers=headers)
    content = json.loads(str(ret.content, encoding='utf-8'))
    return content['token']


def test_api_token_auth():
    url = "http://127.0.0.1:8000/api/api-token-auth/"
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    payload = {
        "username": "admin",
        "password": "admin"
    }

    ret = requests.post(url, data=json.dumps(payload), headers=headers)
    print(str(ret.content, encoding='utf-8'))


def test_servers_post():
    mytoken = get_api_token_auth()
    url = "http://127.0.0.1:8000/api/servers/"
    headers = {'Content-Type': 'application/json;charset=utf-8', 'Authorization': 'Token {}'.format(mytoken)}
    payload = {
        'name': '192.169.10.123_8888',
        'ip_address': '192.168.10.123',
        'port': '8888',
        'salt_name': '192.168.10.123',
        'app_name': 'ZEP-BACKEND-NODEJS',
        'env_name': 'TEST',
        'app_user': 'root'
    }
    ret = requests.post(url, data=json.dumps(payload), headers=headers)
    print(str(ret.content, encoding='utf-8'))


def test_servers_put():
    mytoken = get_api_token_auth()
    url = "http://127.0.0.1:8000/api/servers/83/"
    headers = {'Content-Type': 'application/json;charset=utf-8', 'Authorization': 'Token {}'.format(mytoken)}
    payload = {
        'name': '192.169.10.123_8888',
        'ip_address': '192.168.10.123',
        'port': '8888',
        'salt_name': '192.168.10.123',
        'app_name': 'ZEP-BACKEND-NODEJS',
        'env_name': 'PRD',
        'app_user': 'appuser'
    }
    ret = requests.put(url, data=json.dumps(payload), headers=headers)
    print(str(ret.content, encoding='utf-8'))


def test_users_get():
    url = "http://127.0.0.1:8000/api/users/?format=json"
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    ret = requests.get(url, headers=headers)
    print(str(ret.content, encoding='utf-8'))


if __name__ == '__main__':
    # test_api_token_auth()
    # test_servers_post()
    # test_servers_put()
    test_users_get()
